package com.zmx.patients.view.activity;

/**
 * 时间：2020/5/9 21:17
 * 功能：订单支付界面
 */

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;

import com.bumptech.glide.Glide;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.pojo.OrderDetails;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.utils.BitmapUtil;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OrderPayActivity extends BaseActivity {

    @BindView(R.id.context)
    TextView context;
    @BindView(R.id.head)
    ImageView head;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.describe)
    TextView describe;
    @BindView(R.id.members_number)
    TextView membersNumber;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.radioButton)
    RadioButton radioButton;
    @BindView(R.id.pay_money)
    TextView payMoney;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.cv_item)
    CardView gv;
    private OrderDetails od;
    private String team_id;//专家团的id

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_pay;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        od = (OrderDetails) this.getIntent().getSerializableExtra("od");
        team_id = this.getIntent().getStringExtra("team_id");
        initView();

    }


    public void initView(){

        context.setText(od.getContent());
        name.setText(od.getDoctor().getName());
        describe.setText(od.getDoctor().getTitle_name());
        membersNumber.setText(od.getDoctor().getHosp_name()+"  "+od.getDoctor().getClass_name());
        money.setText(Html.fromHtml("<font color='#FF0000'>￥"+od.getDoctor().getImgtextfee()+"</font>"));
        payMoney.setText(Html.fromHtml("合计 <font color='#FF0000'>￥"+od.getDoctor().getImgtextfee()+"</font>"));
        Glide.with(this).load(od.getDoctor().getAvatar()).into(head);

        if (team_id == null){

            gv.setVisibility(View.VISIBLE);

        }else{

            gv.setVisibility(View.GONE);

        }

    }

    @OnClick({R.id.radioButton, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.radioButton:
                break;
            case R.id.submit:

                if (team_id == null){

                    upload(od.getImage_url());

                }else{

                    uploads(od.getImage_url());
                }

                break;
        }
    }

    private void upload(List<String> selImageList) {// selImageList 包含图片路径的list

        if (selImageList != null) {

            OkHttpClient okHttpClient = new OkHttpClient();

            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM); //表单上传文件

            for (int i = 0; i < selImageList.size(); i++) {

                if (!selImageList.get(i).equals("")) {
                    File file = new File(new BitmapUtil().compressImage(selImageList.get(i))); //根据路径创建file对象
                    builder.addFormDataPart("image[]",
                            file.getName(),
                            RequestBody.create(MediaType.parse("image/jpeg"), file)
                    );
                }

            }

            List<String> l = new ArrayList<>();
            l.add(od.getAsktype());
            l.add(od.getKid());
            l.add(od.getContent());
            l.add(od.getDoctor().getMember_id()+"");
            l.add(od.getIs_call()+"");
            l.add(od.getPatientId());
            l.add("2");

            //post时的参数，后台通过request.getParameter("specialname").toString() 取出
            builder.addFormDataPart("sign", AllUtil.md5(sing(l)));
            builder.addFormDataPart("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            builder.addFormDataPart("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            builder.addFormDataPart("ts", System.currentTimeMillis() / 1000 + "");
            builder.addFormDataPart("cmd", "patientAsk");
            builder.addFormDataPart("data[asktype]", od.getAsktype());
            builder.addFormDataPart("data[content]", od.getContent());
            builder.addFormDataPart("data[doctor_member_id]", od.getDoctor().getMember_id()+"");
            builder.addFormDataPart("data[patient_id]", od.getPatientId());
            builder.addFormDataPart("data[types]", "2");
            builder.addFormDataPart("data[class_id]", od.getKid());
            builder.addFormDataPart("data[is_call]", od.getIs_call()+"");

            RequestBody requestBody = builder.build();
            Request request = new Request.Builder()
                    .url("http://zmx.123xk.cn/app")
                    .post(requestBody)
                    .build();

            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("onFailure: ", e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    try {

                        JSONObject object = new JSONObject(response.body().string());
                        if(object.getString("code").equals("1")){

                            handler.sendEmptyMessage(1);

                        }else{

                            handler.sendEmptyMessage(2);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

        }
    }
    private void uploads(List<String> selImageList) {// selImageList 包含图片路径的list

        Log.e("专家团尽力啊","进来聊聊");

        if (selImageList != null) {

            OkHttpClient okHttpClient = new OkHttpClient();

            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM); //表单上传文件

            for (int i = 0; i < selImageList.size(); i++) {

                if (!selImageList.get(i).equals("")) {
                    File file = new File(new BitmapUtil().compressImage(selImageList.get(i))); //根据路径创建file对象
                    builder.addFormDataPart("image[]",
                            file.getName(),
                            RequestBody.create(MediaType.parse("image/jpeg"), file)
                    );
                }

            }

            List<String> l = new ArrayList<>();
            l.add(od.getAsktype());
            l.add(od.getContent());
            l.add(od.getIs_call()+"");
            l.add(od.getPatientId());
            l.add(team_id+"");

            //post时的参数，后台通过request.getParameter("specialname").toString() 取出
            builder.addFormDataPart("sign", AllUtil.md5(sing(l)));
            builder.addFormDataPart("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            builder.addFormDataPart("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            builder.addFormDataPart("ts", System.currentTimeMillis() / 1000 + "");
            builder.addFormDataPart("cmd", "cerateAsk");
            builder.addFormDataPart("data[asktype]", od.getAsktype());
            builder.addFormDataPart("data[content]", od.getContent());
            builder.addFormDataPart("data[patient_id]", od.getPatientId());
            builder.addFormDataPart("data[team_id]", team_id+"");
            builder.addFormDataPart("data[is_call]", od.getIs_call()+"");

            RequestBody requestBody = builder.build();
            Request request = new Request.Builder()
                    .url("http://zmx.123xk.cn/admin/api.team/entry")
                    .post(requestBody)
                    .build();

            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("onFailure: ", e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    try {

                        JSONObject object = new JSONObject(response.body().string());
                        Log.e("上传错误: ", object.toString());
                        if(object.getString("code").equals("1")){

                            handler.sendEmptyMessage(1);

                        }else{

                            handler.sendEmptyMessage(2);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("上传错误: ", e.toString());
                    }

                }
            });

        }
    }

    private Dialog modify_dialogs;//弹出框

    public void pop_up() {

        View view;//选择性别的view
        RelativeLayout graphic;

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_pay_choose, null);

        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        Button button = view.findViewById(R.id.pay);
        button.setOnClickListener(v -> {

            modify_dialogs.dismiss();
            Intent intent = new Intent();
            intent.setClass(mActivity, PaymentSuccessActivity.class);
            startActivity(intent);

        });

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:

                    pop_up();

                    break;

                case 2:
                    Toast("提问失败");
                    break;

            }
        }
    };

}
